package jumpd

import (
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"os"
)

type WorkConfig struct {
	FileName string `json:"filename"`
	Author   string `json:"author"`
	Project  string `json:"project"`
	Token    string `json:"token"`
}

// type ConfigReadWriter interface {
// 	LoadConfig() bool
// 	Open() bool
// 	Size() (uint64, error)
// 	Read(buf []byte, offset uint64) (n int, err error)
// 	Write(buf []byte) (uint64, error)
// 	WriteAt(buf []byte, offset uint64) (uint64, error)
// 	Close()
// }

type HFD struct {
	Config    *WorkConfig
	CacheSize uint64
}

func (hfd *HFD) Close() {
	// not support
}

func (hfd *HFD) WriteAt(buf []byte, offset uint64) (uint64, error) {
	// not support
	return 0, nil
}

func (hfd *HFD) Write(buf []byte) (uint64, error) {
	// not support
	return 0, nil
}

func (hfd *HFD) Open() bool {
	// not support
	return false
}

func (hfd *HFD) makereq(offset uint64) (*http.Request, error) {
	config := hfd.Config
	author := config.Author
	project := config.Project
	fileName := config.FileName
	token := config.Token

	// url := fmt.Sprintf("https://huggingface.co/%v/%v/resolve/main/%v?download=true", author, project, fileName)
	url := fmt.Sprintf("https://hf-mirror.com/%v/%v/resolve/main/%v?download=true", author, project, fileName)

	// 创建请求
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return nil, fmt.Errorf("error creating request: %v", err)
	}

	// 设置Authorization头
	if len(token) > 0 {
		req.Header.Set("Authorization", "Bearer "+token)
	}

	// 设置断点续传的Range头
	if offset > 0 {
		req.Header.Set("Range", fmt.Sprintf("bytes=%d-", offset))
	}
	return req, nil
}

func (hfd *HFD) Size() (uint64, error) {
	req, err := hfd.makereq(0)
	if err != nil {
		return 0, err
	}

	// 发送请求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return 0, fmt.Errorf("error making request: %v", err)
	}
	defer resp.Body.Close()

	// 检查响应码
	if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusPartialContent {
		if resp.Status == "416 Requested Range Not Satisfiable" {
			fmt.Println("Download is Completed!")
		} else {
			fmt.Printf("Failed to download file: %s\n", resp.Status)
		}
		return 0, errors.New("416 Requested Range Not Satisfiable")
	}

	length := resp.ContentLength
	if length >= 0 {
		return uint64(resp.ContentLength), nil
	}
	return 0, fmt.Errorf("content length is less than 0 : %v", length)
}

func (hfd *HFD) Read(buf []byte, offset uint64) (n int, err error) {

	req, err := hfd.makereq(offset)
	if err != nil {
		return 0, err
	}

	// 发送请求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return 0, fmt.Errorf("error making request: %v", err)
	}
	defer resp.Body.Close()

	// 检查响应码
	if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusPartialContent {
		if resp.Status == "416 Requested Range Not Satisfiable" {
			fmt.Println("Download is Completed!")
		} else {
			fmt.Printf("Failed to download file: %s\n", resp.Status)
		}
		return 0, errors.New("416 Requested Range Not Satisfiable")
	}

	return resp.Body.Read(buf)
}

func (hfd *HFD) LoadConfig() bool {
	// 打开JSON配置文件
	file, err := os.Open("hfd_config.json")
	if err != nil {
		fmt.Printf("Error opening config file: %v\n", err)
		return false
	}
	defer file.Close()

	// 读取文件内容
	byteValue, err := io.ReadAll(file)
	if err != nil {
		fmt.Printf("Error reading config file: %v\n", err)
		return false
	}

	// 定义一个WorkConfig实例
	var config WorkConfig

	// 将JSON数据解析到结构体
	err = json.Unmarshal(byteValue, &config)
	if err != nil {
		fmt.Printf("Error unmarshalling JSON: %v\n", err)
		return false
	}

	fmt.Printf("config: %v\n", config)
	hfd.Config = &config
	return true
}
